from fastapi import FastAPI
from fastapi.middleware.cors import CORSMiddleware
import pandas as pd
import os

# 导入模型预测结果
from models.teaching_pred import teaching_pred_result
from models.student_pred import student_pred_result
from models.course_demand_pred import course_demand_result
from models.teacher_pred import teacher_pred_result


# 数据加载工具函数
def load_json_data(filename: str) -> pd.DataFrame:
    """加载data目录下的JSON数据"""
    current_dir = os.path.dirname(os.path.abspath(__file__))
    file_path = os.path.join(current_dir, "data", filename)
    file_path = os.path.abspath(file_path)

    try:
        with open(file_path, 'r', encoding='utf-8') as f:
            data = pd.read_json(f)
        return data
    except Exception as e:
        print(f"加载数据失败: {e}")
        return pd.DataFrame()


# 初始化FastAPI应用
app = FastAPI(
    title="教学数据分析与预测API",
    description="提供教学质量、学生学业、课程资源和师资结构的数据分析与预测接口",
    version="1.0.0"
)

# 配置CORS，允许前端访问
app.add_middleware(
    CORSMiddleware,
    allow_origins=[
        "http://localhost:8080",  # Vue前端默认地址
        "http://localhost:8081",  # Vue前端实际运行地址
        "http://127.0.0.1:8080",
        "http://127.0.0.1:8081"
    ],
    allow_credentials=True,
    allow_methods=["*"],
    allow_headers=["*"],
)


# ---------------- 教学质量分析接口 ----------------
# @app.get("/api/teaching/evaluation", tags=["教学质量分析"])
# def get_teaching_evaluation():
#     """获取各学期教学评价指标及增长率数据"""
#     df = load_json_data("各学期教学评价指标及增长率.json")
#     return df.to_dict("records")


@app.get("/api/teaching/evaluation", tags=["教学质量分析"])
def get_teaching_evaluation():
    """获取各学期教学评价指标及增长率数据"""
    import pandas as pd
    import numpy as np

    # 加载JSON数据
    df = load_json_data("各学期教学评价指标及增长率.json")

    # 1. 将NaN替换为None（JSON兼容的空值）
    df = df.replace({np.nan: None})

    # 2. 确保所有数值为Python原生类型（避免numpy类型）
    # 转换DataFrame中的数值列到Python原生类型
    for col in df.select_dtypes(include=['float64', 'int64']).columns:
        df[col] = df[col].apply(lambda x: x.item() if pd.notnull(x) else x)

    # 3. 转换为字典列表返回
    return df.to_dict("records")

@app.get("/api/teaching/course-pass-excellent", tags=["教学质量分析"])
def get_course_pass_excellent():
    """获取课程通过率与优秀率数据"""
    df = load_json_data("课程通过率与优秀率数据.json")
    return df.to_dict("records")


@app.get("/api/teaching/college-satisfaction", tags=["教学质量分析"])
def get_college_satisfaction():
    """获取各学院教学满意度评分"""
    df = load_json_data("各学院教学满意度评分.json")
    return df.to_dict("records")


@app.get("/api/teaching/employment-rate", tags=["教学质量分析"])
def get_employment_rate():
    """获取不同专业就业率对比数据"""
    df = load_json_data("不同专业就业率对比.json")
    return df.to_dict("records")


@app.get("/api/teaching/prediction", tags=["教学质量分析"])
def get_teaching_prediction():
    """获取教学评价指标预测结果"""
    return teaching_pred_result


# ---------------- 学生学业分析接口 ----------------
@app.get("/api/student/grade-distribution", tags=["学生学业分析"])
def get_grade_distribution():
    """获取各年级学生成绩分布数据"""
    df = load_json_data("各年级学生成绩分布数据.json")
    return df.to_dict("records")


@app.get("/api/student/course-enrollment", tags=["学生学业分析"])
def get_course_enrollment():
    """获取课程选修人数与评分数据"""
    df = load_json_data("课程选修人数与评分数据.json")
    return df.to_dict("records")


@app.get("/api/student/attendance-score", tags=["学生学业分析"])
def get_attendance_score():
    """获取学生出勤率与成绩相关性数据"""
    df = load_json_data("学生出勤率与成绩相关性.json")
    return df.to_dict("records")


@app.get("/api/student/academic-participation", tags=["学生学业分析"])
def get_academic_participation():
    """获取学生学术活动参与数据"""
    df = load_json_data("学生学术活动参与数据.json")
    return df.to_dict("records")


@app.get("/api/student/prediction", tags=["学生学业分析"])
def get_student_prediction():
    """获取学生成绩预测结果"""
    return student_pred_result


# ---------------- 课程资源分析接口 ----------------
@app.get("/api/course/capacity", tags=["课程资源分析"])
def get_course_capacity():
    """获取各学期课程开设数量与容量数据"""
    df = load_json_data("各学期课程开设数量与容量.json")
    return df.to_dict("records")


@app.get("/api/course/resource-allocation", tags=["课程资源分析"])
def get_resource_allocation():
    """获取教学资源分配情况数据"""
    df = load_json_data("教学资源分配情况.json")
    return df.to_dict("records")


@app.get("/api/course/textbook-evaluation", tags=["课程资源分析"])
def get_textbook_evaluation():
    """获取教材使用频率与评价数据"""
    df = load_json_data("教材使用频率与评价.json")
    return df.to_dict("records")


@app.get("/api/course/equipment-utilization", tags=["课程资源分析"])
def get_equipment_utilization():
    """获取实验设备利用率数据"""
    df = load_json_data("实验设备利用率数据.json")
    return df.to_dict("records")


@app.get("/api/course/demand-prediction", tags=["课程资源分析"])
def get_course_demand_prediction():
    """获取课程需求预测结果"""
    return course_demand_result


# ---------------- 师资结构分析接口 ----------------
@app.get("/api/teacher/age-title", tags=["师资结构分析"])
def get_teacher_age_title():
    """获取教师职称与年龄分布数据"""
    df = load_json_data("教师职称与年龄分布.json")
    return df.to_dict("records")


@app.get("/api/teacher/workload", tags=["师资结构分析"])
def get_teacher_workload():
    """获取教师教学工作量统计数据"""
    df = load_json_data("教师教学工作量统计.json")
    return df.to_dict("records")


@app.get("/api/teacher/research-teaching", tags=["师资结构分析"])
def get_teacher_research_teaching():
    """获取教师科研成果与教学评价数据"""
    df = load_json_data("教师科研成果与教学评价.json")
    return df.to_dict("records")


@app.get("/api/teacher/training", tags=["师资结构分析"])
def get_teacher_training():
    """获取教师培训参与情况数据"""
    df = load_json_data("教师培训参与情况.json")
    return df.to_dict("records")


@app.get("/api/teacher/prediction", tags=["师资结构分析"])
def get_teacher_prediction():
    """获取教师教学效果预测结果"""
    return teacher_pred_result


# 根路径测试接口
@app.get("/", tags=["系统信息"])
def read_root():
    return {
        "message": "教学数据分析与预测API服务已启动",
        "version": "1.0.0",
        "documentation": "/docs"
    }


if __name__ == "__main__":
    import uvicorn
    uvicorn.run("main:app", host="0.0.0.0", port=8000, reload=True)